/****************************************************************************
 * 2025.10 XLB-20250122JTG
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using QAssetBundle;
using UnityEngine.UI;
using QFramework;
using UnityEngine.U2D;

namespace ProjectSurvivor
{
	public partial class TreasureChestPanel : UIElement, IController
	{
		private ResLoader mResLoader = ResLoader.Allocate();
		private void Awake()
		{
			BtnSure.onClick.AddListener(() =>
			{
				AudioKit.PlaySound(Sfx.BUTTONCLICK);
				Time.timeScale = 1.0f;
				this.Hide();
			});
		}

		private void OnEnable()
		{
			var expUpgradeSystem = this.GetSystem<ExpUpgradeSystem>();

			var matchedPairedItems = expUpgradeSystem.Items
				.Where(item => item.IsWeapon)
				.Where(item =>
				{
					if (item.CurrentLevel.Value >= 7)
					{
						bool containsInPair = expUpgradeSystem.Pairs.ContainsKey(item.Key);

						if (!containsInPair) return false;
						
						string pairItemKey = expUpgradeSystem.Pairs[item.Key];
						bool pairItemStartUpgrade =
							expUpgradeSystem.DictionaryExpUpgradeItems[pairItemKey].CurrentLevel.Value > 0;
						
						bool pairedUnlocked = expUpgradeSystem.PairsProperties[item.Key].Value;
						
						return containsInPair && pairItemStartUpgrade && !pairedUnlocked;
					}

					return false;
				});

			if (matchedPairedItems.Any())
			{
				var item = matchedPairedItems.ToList().GetRandomItem();
				Content.text = $"<b>合成后的{item.PairedName}</b>\n{item.PairedDescription}";

				while (!item.UpgradeFinish)
				{
					item.Upgrade();
				}

				Icon.sprite = mResLoader.LoadSync<SpriteAtlas>("icon").GetSprite(item.PairedIconName);
				Icon.Show();

				expUpgradeSystem.PairsProperties[item.Key].Value = true;
			}
			else
			{
				var upgradeItems = expUpgradeSystem.Items.Where(item => item.CurrentLevel.Value > 0 && !item.UpgradeFinish).ToList();

				if (upgradeItems.Any())
				{
					var item = upgradeItems.GetRandomItem();
					Content.text = item.Description;
					
					Icon.sprite = mResLoader.LoadSync<SpriteAtlas>("icon").GetSprite(item.IconName);
					Icon.Show();
					
					item.Upgrade();
				}
				else if(Global.HP.Value < Global.MaxHP.Value)
				{
					Content.text = "恢复 1 点血量";
					AudioKit.PlaySound(Sfx.HP);
					Global.HP.Value += 1;
					Icon.Hide();
				}
				else
				{
					Content.text = "增加 50 金币！";
					Global.Coin.Value += 50;
					Icon.Hide();
				}
			}
		}

		protected override void OnBeforeDestroy()
		{
			mResLoader.Recycle2Cache();
			mResLoader = null;
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}